package com.xyy.kingdeek3cloud.service.impl.jd;

import com.alibaba.fastjson.JSON;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.xyy.kingdeek3cloud.config.ComentCfg;
import com.xyy.kingdeek3cloud.entity.OrderUnitEntity;
import com.xyy.kingdeek3cloud.entity.erp.JdProductInfo;
import com.xyy.kingdeek3cloud.entity.erp.OrderTax;
import com.xyy.kingdeek3cloud.entity.erp.OrgGoods;
import com.xyy.kingdeek3cloud.entity.pop.PopErpClientInfoDto;
import com.xyy.kingdeek3cloud.entity.pop.PopErpSkuForInsertDto;
import com.xyy.kingdeek3cloud.entity.pop.PopErpSkuStockV2Dto;
import com.xyy.kingdeek3cloud.entity.pop.SellerOrderDeliverDetailDto;
import com.xyy.kingdeek3cloud.enums.K3FromEnum;
import com.xyy.kingdeek3cloud.helper.JdHelper;
import com.xyy.kingdeek3cloud.service.KingdeeService;
import com.xyy.kingdeek3cloud.utils.CfgUtils;
import com.xyy.kingdeek3cloud.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyy.kingdeek3cloud.utils.DateUtils.SHORT_DATE_FORMAT_STR;

@Service
@Slf4j
public class KingdeeServiceImpl implements KingdeeService {
    private ComentCfg kingCfg = CfgUtils.getAppDefaultCfg();
   // @Value("${king.ckId}")
    private String warehouseCode = kingCfg.getJdCkId();

   // @Value("${pop.orgId}")
    private String popOrgId = kingCfg.getOrgId();

    @Override
    public OrderUnitEntity JdOrderProductInfo(String number) {
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFormId(K3FromEnum.BD_MATERIAL.getName());
        queryParam.setFieldKeys("FSaleUnitId.fnumber,FSalePriceUnitId.fnumber,FStoreUnitID.fnumber");
        queryParam.setFilterString("Fnumber='" + number + "'");
        try {
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            OrderUnitEntity orderUnitEntity = new OrderUnitEntity();

            for (List<Object> list : lists) {
                //销售单位
                orderUnitEntity.setFUnitID(String.valueOf(list.get(0)));

                //销售单位
                orderUnitEntity.setFPriceUnitId(String.valueOf(list.get(1)));

                //销售单位
                orderUnitEntity.setFStockUnitID(String.valueOf(list.get(2)));
            }

            return orderUnitEntity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //查询金蝶客户信息
    @Override
    public List<PopErpClientInfoDto> JdClientInfo() {
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFormId(K3FromEnum.BD_CUSTOMER.getName());
        queryParam.setFieldKeys("FName,FNumber");
        queryParam.setOrderString("fnumber desc");
        queryParam.setFilterString("FDocumentStatus='C'");
        queryParam.setLimit(2000);
        try {
            List<PopErpClientInfoDto> list = new ArrayList<>();
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            for (List<Object> objects : lists) {
                PopErpClientInfoDto erpClientInfoDto = new PopErpClientInfoDto();
                erpClientInfoDto.setOrgId(popOrgId);
                erpClientInfoDto.setCustomerId(String.valueOf(objects.get(1)));
                erpClientInfoDto.setCustomerCode(String.valueOf(objects.get(1)));
                erpClientInfoDto.setCustomerName(String.valueOf(objects.get(0)));
                list.add(erpClientInfoDto);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<PopErpSkuForInsertDto> JdProductInfo() {
        List<PopErpSkuStockV2Dto> stockV2Dtos = QueryInventory(null);
        List<String> collect2 = stockV2Dtos.stream().map(m -> "'" + m.getErpCode() + "'").collect(Collectors.toList());
        String join1 = String.join(",", collect2);
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFieldKeys("fnumber,FName,FMinPackCount,FSpecification,FStoreUnitID.fname,F_KBL_Assistant.fdatavalue,FExpPeriod");
        queryParam.setFilterString("fnumber in (" + join1 + ") ");
        queryParam.setFormId(K3FromEnum.BD_MATERIAL.getName());
        try {
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            List<JdProductInfo> collect = lists.stream().map(m -> {
                JdProductInfo jdProductInfo = new JdProductInfo();
                jdProductInfo.setFnumber(String.valueOf(m.get(0)));
                jdProductInfo.setFName(String.valueOf(m.get(1)));
                jdProductInfo.setFMinPackCount(String.valueOf(m.get(2)));
                jdProductInfo.setFSpecification(String.valueOf(m.get(3)));
                jdProductInfo.setFStoreUnitID(String.valueOf(m.get(4)));
                jdProductInfo.setF_KBL_Assistant(String.valueOf(m.get(5)));
                jdProductInfo.setFExpPeriod(String.valueOf(m.get(6)));
                return jdProductInfo;
            }).collect(Collectors.toList());
            List<PopErpSkuForInsertDto> popErpSkuForInsertDtos = new ArrayList<>();
            //pop商品转换
            for (JdProductInfo jdProductInfo : collect) {
                PopErpSkuForInsertDto popErpSkuForInsertDto = new PopErpSkuForInsertDto();
                popErpSkuForInsertDto.setErpCode(jdProductInfo.getFnumber());
                popErpSkuForInsertDto.setProductName(jdProductInfo.getFName());
                popErpSkuForInsertDto.setCommonName(jdProductInfo.getFName());
                popErpSkuForInsertDto.setApprovalNumber("-");
                popErpSkuForInsertDto.setCode("0");
                popErpSkuForInsertDto.setManufacturer("湖南康宝林药业有限公司");
                popErpSkuForInsertDto.setMediumPackageNum(Double.valueOf(jdProductInfo.getFMinPackCount()).intValue());
                popErpSkuForInsertDto.setProductUnit(jdProductInfo.getFStoreUnitID());
                popErpSkuForInsertDto.setSpec(jdProductInfo.getFSpecification());
                popErpSkuForInsertDto.setTerm(String.valueOf(Integer.parseInt(jdProductInfo.getFExpPeriod()) * 12));
                popErpSkuForInsertDto.setProductionArea("");
                popErpSkuForInsertDto.setDosageForm(jdProductInfo.getF_KBL_Assistant());
                popErpSkuForInsertDto.setOldestProDate(DateUtils.format(DateUtils.getBeginDayOfYear(), SHORT_DATE_FORMAT_STR));
                popErpSkuForInsertDto.setNewProDate(DateUtils.format(DateUtils.getBeginDayOfYear(), SHORT_DATE_FORMAT_STR));
                popErpSkuForInsertDto.setNearEffect(DateUtils.format(DateUtils.getEndDayOfYear(), SHORT_DATE_FORMAT_STR));
                popErpSkuForInsertDto.setFarEffect(DateUtils.format(DateUtils.getEndDayOfYear(), SHORT_DATE_FORMAT_STR));
                popErpSkuForInsertDtos.add(popErpSkuForInsertDto);
            }
            //构造查询接口
            List<String> collect1 = popErpSkuForInsertDtos.stream().map(m -> "'" + m.getErpCode() + "'").collect(Collectors.toList());
            String join = String.join(",", collect1);
            List<OrgGoods> orgGoods = JdHelper.QueryOrigin(join, warehouseCode);
            for (PopErpSkuForInsertDto popErpSkuForInsertDto : popErpSkuForInsertDtos) {
                for (OrgGoods orgGood : orgGoods) {
                    if (popErpSkuForInsertDto.getErpCode().equals(orgGood.getNumber())) {
                        popErpSkuForInsertDto.setProductionArea(orgGood.getOrgName());
                    }
                }
            }

            return popErpSkuForInsertDtos;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public List<PopErpSkuStockV2Dto> QueryInventory(String join) {
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFormId(K3FromEnum.STK_INVENTORY.getName());
        queryParam.setFieldKeys("FMaterialId.Fnumber,FBaseQty");
        if (!StringUtils.isEmpty(join)) {
            queryParam.setFilterString("FStockId.fnumber in (" + warehouseCode + ") and FMaterialId.Fnumber in (" + join + ")");
        } else {
            queryParam.setFilterString("FStockId.fnumber in (" + warehouseCode + ") and FBaseQty>0");
        }
        try {
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            return JdHelper.convertToPopSkuStockDto(lists);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> QueryJdSalesOrder(List<String> list) {
        List<String> orders = new ArrayList<>();
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFormId(K3FromEnum.SAL_SALEORDER.getName());
        queryParam.setFieldKeys("F_KBL_Text,FDocumentStatus");
        List<String> collect = list.stream().map(m -> "'" + m + "'").collect(Collectors.toList());
        String join = String.join(",", collect);
        queryParam.setFilterString("FDocumentStatus='C' and F_KBL_Text in (" + join + ") ");
        try {
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            if (lists.size() != 0) {
                for (List<Object> objects : lists) {
                    orders.add(String.valueOf(objects.get(0)));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return orders;

    }

    @Override
    public List<SellerOrderDeliverDetailDto> QueryJdDeliveryOrder(List<String> list) {
        List<String> collect = list.stream().map(m -> "'" + m + "'").collect(Collectors.toList());
        String join = String.join(",", collect);
        List<SellerOrderDeliverDetailDto> sellerOrderDeliverDetailDtos = new ArrayList<>();
        try {
            K3CloudApi k3CloudApi = new K3CloudApi();
            QueryParam queryParam = new QueryParam();
            queryParam.setFormId(K3FromEnum.SAL_OUTSTOCK.getName());
            queryParam.setFilterString("FDocumentStatus='C' and F_KBL_Text in (" + join + ")");
            queryParam.setFieldKeys("F_KBL_Text,F_KBL_Text1,FMaterialID.FNumber,FMaterialName,FLot.FNumber,FRealQty,FExpiryDate,FProduceDate,FPrice");
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));
            log.info("金蝶查询出库单响应数据:{}", JSON.toJSONString(lists));
            if (lists.size() != 0) {
                for (List<Object> objects : lists) {
                    SellerOrderDeliverDetailDto popDetail = new SellerOrderDeliverDetailDto();
                    popDetail.setOrderNo(String.valueOf(objects.get(0)));
                    popDetail.setOrderDetailId(Long.parseLong(String.valueOf(objects.get(1))));
                    popDetail.setErpCode(String.valueOf(objects.get(2)));
                    popDetail.setProductName(String.valueOf(objects.get(3)));
                    popDetail.setBatchCode(String.valueOf(objects.get(4)));
                    BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble(String.valueOf(objects.get(5))));
                    popDetail.setBatchNum(bigDecimal);
                    popDetail.setBatchNumDecimal(bigDecimal);
                    popDetail.setBatchValidDate(DateUtils.parserShortDate(String.valueOf(objects.get(6)), SHORT_DATE_FORMAT_STR));
                    popDetail.setProductionDate(DateUtils.parserShortDate(String.valueOf(objects.get(7)), SHORT_DATE_FORMAT_STR));
                    BigDecimal price = BigDecimal.valueOf(Double.parseDouble(String.valueOf(objects.get(8))));
                    popDetail.setBatchPrice(price);
                    sellerOrderDeliverDetailDtos.add(popDetail);
                }
            } else {
                return new ArrayList<>();
            }
        } catch (Exception e) {
            return new ArrayList<>();
        }
        return sellerOrderDeliverDetailDtos;
    }

    @Override
    public OrderTax QueryBatchNumber(String number, String ckId) {
        String code = "'" + number + "'";
        K3CloudApi k3CloudApi = new K3CloudApi();
        QueryParam queryParam = new QueryParam();
        queryParam.setFieldKeys("FAUXPROPID.FF100001.Fnumber,FMaterialId.Fnumber,FLot.Fnumber,FProduceDate,FExpiryDate,FBaseQty");
        queryParam.setFilterString("FStockId.fnumber in(" + ckId + ") and FMaterialId.fnumber in (" + code + ") and FBaseQty>0");
        queryParam.setFormId(K3FromEnum.STK_INVENTORY.getName());
        try {
            List<List<Object>> lists = k3CloudApi.executeBillQuery(JSON.toJSONString(queryParam));

            List<OrderTax> collect = lists.stream().map(m -> {
                OrderTax orderTax = new OrderTax();
                orderTax.setProducingArea(String.valueOf(m.get(0)));
                orderTax.setNumber(String.valueOf(m.get(1)));
                orderTax.setBatch(String.valueOf(m.get(2)));
                orderTax.setProdDate(String.valueOf(m.get(3)));
                orderTax.setValDate(String.valueOf(m.get(4)));
                orderTax.setFBaseQty(BigDecimal.valueOf(Double.parseDouble(String.valueOf(m.get(5)))));
                return orderTax;
            }).collect(Collectors.toList());
            return collect.stream().min(Comparator.comparing(OrderTax::getProdDate)).orElse(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }


}
